package com.edu.ujn.myh.utils;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import org.apache.tools.zip.*;;

public class ZipUtils {
	
//	将文件打包成zip
	public static boolean zipFile(List fileList,String fileName){
		File isFile = new File(fileName);
		if(isFile.exists()){
			isFile.delete();
		}
		ZipOutputStream zos;
		try {
			zos = new ZipOutputStream(new FileOutputStream(fileName));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			return false;
		}
		int readLen = 0;
		byte buffer[] = new byte[1024];
		for(int i=0;i<fileList.size();i++){
			File file = (File)fileList.get(i);
			if (!file.exists()){
				continue;
			}
			String tempName = file.getName();
			String name[] = tempName.split("&File&");
			System.out.println(name[1]);
			ZipEntry ze = new ZipEntry(name[1]);
			ze.setSize(file.length());//设置压缩文件的大小
			ze.setTime(file.lastModified());//设置压缩文件的修改时间
			try {
				zos.putNextEntry(ze);
			} catch (IOException e) {
				e.printStackTrace();
				return false;
			}
			InputStream in = null;
			try {
				in = new BufferedInputStream(new FileInputStream(file));
			} catch (FileNotFoundException e) {
				e.printStackTrace();
				return false;
			}
			try {
				while((readLen = in.read(buffer,0,1024))!=-1){
					zos.write(buffer,0,readLen);
				}
				in.close();
			} catch (IOException e) {
				e.printStackTrace();
				return false;
			}
			
		}
		try {
			zos.close();
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}

}
